Page({
  data: {
    prompt: '',
    negativePrompt: '',
    isGenerating: false,
    styleTags: [
      '写实', '动漫', '电影感', '梦幻', 
      '水彩', '科幻', '插画', '古风'
    ]
  },

  onLoad() {
    // Check login status
    const app = getApp<{
      globalData: {
        isLoggedIn: boolean;
      };
    }>();
    
    if (!app.globalData.isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再创建图片',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '/pages/profile/index'
          });
        }
      });
    }
  },

  // Add style tag to prompt
  onTagTap(e: any) {
    const tag = e.currentTarget.dataset.tag;
    let currentPrompt = this.data.prompt || '';
    
    // Add the tag to the prompt with a comma if needed
    if (currentPrompt && currentPrompt.trim() !== '') {
      // 只有当当前提示词不是空的时候才添加逗号
      if (!currentPrompt.endsWith('，') && !currentPrompt.endsWith(',')) {
        currentPrompt += '，';
      }
      currentPrompt += tag;
    } else {
      // 如果当前提示词为空，直接设置为选中的标签
      currentPrompt = tag;
    }
    
    this.setData({
      prompt: currentPrompt
    });
  },

  // Use example prompt
  onUseExample(e: any) {
    const example = e.currentTarget.dataset.example;
    
    this.setData({
      prompt: example
    });
  },

  // Generate image from prompt
  onGenerateImage(e: any) {
    const { prompt, negativePrompt } = e.detail.value;
    
    // Validate prompt
    if (!prompt || prompt.trim() === '') {
      wx.showToast({
        title: '请输入提示词',
        icon: 'error'
      });
      return;
    }
    
    this.setData({ isGenerating: true });
    
    const self = this;
    // 使用回调方式调用云函数
    wx.cloud.callFunction({
      name: 'imageGenerator',
      data: {
        action: 'createImageTask',
        data: {
          prompt: prompt,
          negativePrompt: negativePrompt || '',
          size: '1024*1024',
          n: 1
        }
      },
      success(res: any) {
        const result = res.result;
        
        if (result && result.success && result.taskId) {
          // Navigate to result page with the taskId
          wx.navigateTo({
            url: `/pages/imageResult/index?taskId=${result.taskId}&prompt=${encodeURIComponent(prompt)}&negativePrompt=${encodeURIComponent(negativePrompt || '')}`
          });
        } else {
          let errorMsg = '创建任务失败';
          if (result && result.message) {
            errorMsg = result.message;
          }
          wx.showToast({
            title: errorMsg,
            icon: 'error'
          });
          console.error('创建任务失败', result);
        }
      },
      fail(err) {
        console.error('生成图片失败:', err);
        wx.showToast({
          title: '生成失败',
          icon: 'error'
        });
      },
      complete() {
        self.setData({ isGenerating: false });
      }
    });
  }
}); 